import axios from "axios";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { getCookie, setCookieWithSeconds } from "@/utils/public";
import { refresh_Token } from "@/api/user.js";

//刷新token
const async_refreshToken = async (Refresh_token) => {
  isRefreshing.value = true;
  const res = await refresh_Token({
    platformId: "e92ee242-497f-4077-9ba7-462265a6d03b",
    refreshToken: Refresh_token,
  });
  if (res.code === 200) {
    isRefreshing.value = false;
    console.log("刷新token", res);
    // 名称 值 过期时间
    setCookieWithSeconds(
      "access_token",
      res.data.access_token,
      res.data.expires_in
    );
    setCookieWithSeconds(
      "refresh_token",
      res.data.refresh_token,
      res.data.expires_in
    );
    setCookieWithSeconds("uid", res.data.uid, res.data.expires_in);
    // 处理token时间
    var new_expires_in = "";
    if (res.data.expires_in) {
      var date = new Date();
      date.setTime(date.getTime() + res.data.expires_in * 1000);
      new_expires_in = date.toUTCString();
    }
    setCookieWithSeconds(
      "token_expires_in",
      new_expires_in,
      res.data.expires_in
    );
  }
};

const refreshToken = async () => {
  let oldRefresh_token = getCookie("refresh_token");
  let oldPlatformId = getCookie("uid");
  await async_refreshToken(oldRefresh_token, oldPlatformId);
};

// // 检查token剩余时间的函数
function _isRefresh_token() {
  let token_expires_in = getCookie("token_expires_in");
  const old_token_expires_in = new Date(token_expires_in);
  const nowDate = new Date();
  let diff = old_token_expires_in - nowDate;
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  // console.log(`${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`);
  return minutes;
}

// 清除所有cookie
const clearAllCookies = () => {
  var cookies = document.cookie.split(";");
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    var eqPos = cookie.indexOf("=");
    var name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
  }
};

// // 创建axios实例
const instance = axios.create({
  // process.env.NODE_ENV === "development" ? "测试/开发地址" : "生产环境地址"

  // baseURL:
  //   process.env.NODE_ENV === "development"
  //     ? "/api"
  //     : "https://59.203.83.242:8090", //淮北
  baseURL:
    process.env.NODE_ENV === "development"
      ? "/api"
      : "https://10.10.102.139:8090", //淮南
  // timeout: 5000  //请求超时时间
});

const retryRequest = ref(null);
//请求拦截器
instance.interceptors.request.use((config) => {
  const access_token = getCookie("access_token");
  // console.log("access_token", access_token);
  if (access_token) {
    config.headers["token"] = access_token;
  }

  retryRequest.value = config;
  return config;
});

let isRefreshing = ref(false); //是否在刷新token
let requests = []; // 重试队列，每一项将是一个待执行的函数形式

// // 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 如果diff_time小于10分钟，更新本地存储中的Token
    let diff_time = _isRefresh_token(); //返回剩余过期的分钟
    //diff_time < 59
    if (response.data.code == 302) {
      const config = response.config;
      console.log(diff_time);

      if (!isRefreshing.value) {
        refreshToken(); //刷新token
      }
    }
    if (
      [
        2001, 401, 404, 422, 500, 5001, 1001, 1002, 1003, 3001, 30011, 3002,
        30021, 3003, 3004, 3005,
      ].includes(response.data.code)
    ) {
      let msg =
        response.data.code == 500 || response.data.code == 5001
          ? "服务器内部错误"
          : response.data.message || "";

      ElMessage({
        message: `${msg}`,
        type: "error",
        showClose: true,
      });
    }
    if (response.data.code == 301) {
      /**
       * 跳往登录页
       */
      ElMessage({
        message: "token过期了，请重新登录",
        type: "error",
        showClose: true,
      });
      clearAllCookies(); //清楚当前游览器所有cookie
      sessionStorage.clear();
      let urlWithoutParams = window.location.href.replace(/(\?.*)?(#.*)?$/, "");
      //urlWithoutParams='https://59.203.83.242:8090/uap'
      console.log("登出--系统回调地址", urlWithoutParams);
      window.location.href = `http://iam.ah.cegn.cn/idp/authCenter/GLO?redirectToUrl=${urlWithoutParams}&redirectToLogin=true&entityId=d9dde4457d904d9aa071150f35187215`;
      clearAllCookies(); //清楚当前游览器所有cookie
      sessionStorage.clear();
    }
    // console.log("response.data", response.data);
    return response.data;
  },
  (err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = "请求错误";
          break;
        case 401:
          err.message = "未授权，请登录";
          break;
        case 403:
          err.message = "登陆超时，请重新登陆";
          break;
        case 404:
          err.message = `请求地址出错`; //: ${err.response.config.url}
          break;
        case 408:
          err.message = "请求超时";
          break;
        case 500:
          err.message = "服务器内部错误";
          break;
        case 501:
          err.message = err.response.data || "服务未实现";
          break;
        case 502:
          err.message = "网关错误";
          break;
        case 503:
          err.message = "服务不可用";
          break;
        case 504:
          err.message = "网关超时";
          break;
        case 505:
          err.message = "HTTP版本不受支持";
          break;
        default:
          err.message = "未知错误";
      }
      ElMessage({
        message: `${err.message}`,
        type: "error",
      });
    }
  }
);

// 导出axios实例以及常用的请求方法
export const get = (url, params) => instance.get(url, { params });
export const post = (url, params) => instance.post(url, params);
export const put = (url, params) => instance.put(url, params);

export default instance;
